// src/main/java/com/example/filter/AuthenticationFilter.java
package com.example.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

@WebFilter("/*")
public class AuthenticationFilter implements Filter {

    // 普通用户可访问的页面（登录后即可访问）
    private static final String[] USER_PATHS = {
            "/jsp/Homepage.jsp",
            "/jsp/transaction.jsp",
            "/jsp/rental.jsp",
            "/jsp/decrease.jsp",
            "/jsp/increase.jsp"
    };

    // 管理员专属页面（必须 admin 登录）
    private static final String[] ADMIN_PATHS = {
            "/jsp/AdminHomepage.jsp",
            "/jsp/Admintransaction.jsp",
            "/jsp/Adminrental.jsp",
            "/jsp/Admindecrease.jsp",
            "/jsp/Adminincrease.jsp",
            "/jsp/Manage.jsp"
    };

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpSession session = httpRequest.getSession(false);

        String path = httpRequest.getServletPath();

        // 判断是否是管理员页面
        if (isAdminPath(path)) {
            // 管理员页面需要 admin 登录
            if (session == null || session.getAttribute("admin") == null) {
                httpResponse.sendRedirect(httpRequest.getContextPath() + "/login.jsp");
                return;
            }
        }
        // 判断是否是普通用户页面
        else if (isUserPath(path)) {
            // 普通页面只需 user 或 admin 登录
            if (session == null || (session.getAttribute("user") == null && session.getAttribute("admin") == null)) {
                httpResponse.sendRedirect(httpRequest.getContextPath() + "/login.jsp");
                return;
            }
        }

        // 继续请求处理
        chain.doFilter(request, response);
    }

    // 判断是否是管理员页面
    private boolean isAdminPath(String path) {
        for (String adminPath : ADMIN_PATHS) {
            if (path.equals(adminPath)) {
                return true;
            }
        }
        return false;
    }

    // 判断是否是普通用户页面
    private boolean isUserPath(String path) {
        for (String userPath : USER_PATHS) {
            if (path.equals(userPath)) {
                return true;
            }
        }
        return false;
    }
}

